package com.bzyd.mp.datascope;

import com.baomidou.mybatisplus.extension.plugins.handler.DataPermissionHandler;
import com.bzyd.mp.datascope.strategy.DataScopeStrategy;
import com.bzyd.mp.utils.UserContextUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.HexValue;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * mybatis plus数据权限处理器
 */
@Slf4j
public class DataScopePermissionHandler implements DataPermissionHandler {

    @Autowired
    private DataScopeStrategyFactory dataScopeStrategyFactory;

    @Override
    public Expression getSqlSegment(Expression where, String mappedStatementId) {
        String currentUser = UserContextUtil.getCurrentUser();
        if (StringUtils.isBlank(currentUser)) {
            throw new IllegalArgumentException("当前登录用户为空");
        }

        //超级管理员直接放行
        if ("admin".equals(currentUser)) {
            return where;
        }

        DataScopeParam dataScopeParam = DataScopeContextHolder.get();
        if (dataScopeParam == null) {
            return where;
        }

        DataScopeStrategy dataScopeStrategy = dataScopeStrategyFactory.getDataScopeStrategy(dataScopeParam.getMode());
        if (dataScopeStrategy == null) {
            return where;
        }

        if (where == null) {
            where = new HexValue(" 1 = 1 ");
        }
        log.debug("where = {}", where);
        Expression expression = dataScopeStrategy.buildWhere(where, mappedStatementId, dataScopeParam);
        log.debug("expression = {}", expression);
        return expression;
    }
}
